/*
 * FontSelector.java - Font selector
 */

package org.lex.swing.fontchooser.jedit;

import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 * A font chooser widget.
 */
public class FontChooserButton extends JButton {
	/**
	 * Creates a new font selector control.
	 * 
	 * @param font
	 *            The font
	 */
	public FontChooserButton(Font font) {
		setFont(font);
		setRequestFocusEnabled(false);
		addActionListener(new ActionHandler());
		updateText();
	}

	private void updateText() {
		Font font = getFont();
		String styleString;
		switch (font.getStyle()) {
		case Font.PLAIN:
			styleString = "Plain";
			break;
		case Font.BOLD:
			styleString = "Bold";
			break;
		case Font.ITALIC:
			styleString = "Italic";
			break;
		case Font.BOLD | Font.ITALIC:
			styleString = "Bold italic";
			break;
		default:
			styleString = "UNKNOWN!!!???";
			break;
		}

		setText(font.getName() + " " + font.getSize() + " " + styleString);
	}

	class ActionHandler implements ActionListener {
		public void actionPerformed(ActionEvent evt) {
			Font font;

			Window dialog = (Window) SwingUtilities.getAncestorOfClass(Window.class, FontChooserButton.this);
			if (dialog == null) {
				font = new FontChooserDialog(JOptionPane.getFrameForComponent(FontChooserButton.this), getFont()).getSelectedFont();
			} else {
				font = new FontChooserDialog(dialog, getFont()).getSelectedFont();
			}

			if (font != null) {
				setFont(font);
				updateText();
			}
		}
	}
}
